package com.feige.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.feige.annotation.LoginUser;
import com.feige.constant.Constants;
import com.feige.pojo.User;
import com.feige.pojo.dto.ForgetPwd;
import com.feige.pojo.dto.FriendDto;
import com.feige.pojo.dto.PwdDto;
import com.feige.pojo.vo.ChatUserVo;
import com.feige.result.AjaxResult;
import com.feige.result.R;
import com.feige.service.UserService;
import com.feige.utils.jwt.JwtInfo;
import com.feige.utils.jwt.JwtUtils;
import com.feige.utils.redis.RedisUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author feige
 * @since 2020-11-20
 */
@Api(value = "用户表 前端控制器")
@RestController
@RequestMapping("/chat/user")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private RedisUtils redisUtils;

    @Resource
    private JwtUtils jwtUtils;


    @ApiOperation(value = "通过ID查询用户信息")
    @GetMapping("/{id}")
    public AjaxResult getUserInfo(@PathVariable String id){
        User user = userService.getById(id);
        return AjaxResult.success(user);

    }

    @ApiOperation(value = "通过name用户信息")
    @GetMapping("/user/{name}")
    public AjaxResult getChatUserByName(@PathVariable String name, @RequestHeader("token") String token){
        String userId = jwtUtils.getUserIdByToken(token);
        List<ChatUserVo> userVos = userService.getChatUserByName(name,userId);
        if (userVos.isEmpty()){
            return AjaxResult.error(5000,"未查询到数据");
        }
        return AjaxResult.success(userVos);
    }

    @ApiOperation(value = "通过邮箱查询用户")
    @GetMapping("/get/{email}")
    public R<User> getUserByEmail(@PathVariable String email){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("email",email);
        return R.ok(userService.getOne(wrapper));
    }

    @ApiOperation(value = "修改用户")
    @PutMapping("/update")
    public AjaxResult update(@RequestBody User user){
        if ("教师".equals(user.getRole()) && StrUtil.isBlank(userService.checkEmailAuthorize(user.getEmail()))){
            return AjaxResult.error(5000,"该邮箱未授予教师权限，请选择学生角色或联系管理员获取授权");
        }
        boolean update = userService.updateById(user);
        String key = Constants.LOGIN_USER_KEY + user.getId();
        redisUtils.set(key,user);
        if (update) {
            return AjaxResult.success();
        }else {
            return AjaxResult.error();
        }
    }
    @ApiOperation(value = "查询聊天用户")
    @GetMapping("/get/chat-user/{pageNum}/{userId}")
    public AjaxResult getChatUser(@PathVariable String userId, @PathVariable Integer pageNum){
        List<ChatUserVo> chatUserVos = userService.getChatUser(pageNum,userId);
        int total = userService.getChatUserTotal(userId);
        AjaxResult success = AjaxResult.success(chatUserVos);
        success.put("total",total);
        return success;
    }

    @ApiOperation(value = "查询同一个班级的学生")
    @GetMapping("/get/student/{pageNum}/{clazzId}")
    public AjaxResult getStudentByClazzId(@PathVariable String clazzId, @PathVariable Integer pageNum){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.select("id","num","name").eq("clazz_id",clazzId);
        Page<User> page = new Page<>(pageNum,Constants.PAGE_SIZE * 4);
        userService.page(page,wrapper);
        AjaxResult success = AjaxResult.success(page.getRecords());
        success.put("total",page.getTotal());
        return success;
    }

    @ApiOperation(value = "添加好友")
    @PostMapping("/add-friend")
    public AjaxResult addFriend(@RequestBody FriendDto friendDto) {
        boolean flag = userService.addFriend(friendDto);
        if (flag) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error();
        }
    }

    @ApiOperation(value = "删除好友")
    @PostMapping("/delete-friend")
    public AjaxResult deleteFriend(@RequestBody FriendDto friendDto) {
        boolean flag = userService.deleteFriend(friendDto);
        if (flag) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error();
        }
    }


    @ApiOperation(value = "加入一个班级")
    @PutMapping("/join/{userId}/{clazzId}")
    public AjaxResult joinClazz(@PathVariable String userId, @PathVariable String clazzId){
        AjaxResult ajaxResult = userService.jointClazz(userId, clazzId);
        String key = Constants.GROUP_USER_ID_KEY + clazzId;
        // 群聊需要，可以查看ChatHandler.java
        // 保证缓存的中的用户ID和MySQL的一致
        boolean hasKey = redisUtils.hasKey(key);
        if (hasKey) {
            redisUtils.lSet(key,userId);
        }
        return ajaxResult;
    }

    @ApiOperation(value = "退出班级")
    @PutMapping("/exit/{userId}/{clazzId}")
    public AjaxResult exitClazz(@PathVariable String userId, @PathVariable String clazzId){
        return userService.exitClazz(userId,clazzId);
    }

    @ApiOperation(value = "修改密码")
    @PutMapping("/change/pwd")
    public AjaxResult changePwd(@RequestHeader("token") String token,@Validated @RequestBody PwdDto pwdDto){
        String userId = jwtUtils.getUserIdByToken(token);
        return userService.changePwd(userId,pwdDto);
    }


    @ApiOperation(value = "忘记密码")
    @PutMapping("/forget/pwd")
    public AjaxResult forgetPwd(@Validated @RequestBody ForgetPwd forgetPwd){
        return userService.forgetPwd(forgetPwd);
    }
    @ApiOperation(value = "保存用户")
    @PostMapping("/save")
    public R<User> save(@RequestBody User user){
        return R.isOk(userService.save(user));
    }

    @ApiOperation(value = "检查邮箱是否授予教师权限")
    @GetMapping("/check/{email}")
    public R<String> checkEmailAuthorize(@PathVariable("email") String email){
        return R.ok(userService.checkEmailAuthorize(email));
    }

    @PutMapping("/de/{id}")
    R<User> updateDefault(@PathVariable("id") String id){
        UpdateWrapper<User> wrapper = new UpdateWrapper<>();
        wrapper.eq("clazz_id",id);
        User user = new User();
        user.setClazzId("0");
        return R.isOk(userService.update(user,wrapper));
    }


}

